#include <linux/init.h>
#include <linux/module.h>
#include <linux/miscdevice.h>
#include <linux/fs.h>
#include <linux/kernel.h>



static int misc_open(struct inode* inode, struct file* file)
{
    printk("misc_dev is opened\n");
    //打印调用堆栈
    dump_stack();
    return 0;
}

static ssize_t misc_read(struct file* file, \
char __user* buf, size_t size, loff_t* off)
{
    printk("misc_dev is read\n");
    return 0;
}

static  ssize_t misc_write(struct file* file, \
const char __user* buf, size_t size, loff_t* off)
{
    printk("misc_dev is written\n");
    return 0;
}

static int misc_release(struct inode* inode, struct file* file)
{
    return 0;
}

// 定义设备操作函数
static struct file_operations misc_op = {
    .owner   = THIS_MODULE,
    .open    = misc_open,
    .read    = misc_read,
    .write   = misc_write,
    .release = misc_release
};

//定义杂项设备结构体
static struct miscdevice misc_dev = {
    //动态分配次设备号
    .minor = MISC_DYNAMIC_MINOR,
    //杂项设备名称
    .name  = "misc_device",
    //文件接口集
    .fops = &misc_op
};

static int __init misc_init(void)
{
    //返回值用于判断 调用是否出错
    int ret = 0;
    ret = misc_register(&misc_dev);
    if (ret < 0)
    {
        printk("The registration of miscellaneous devices failed\n");
        return -1;
    }
    printk("The registration of miscellaneous devices sucess.\n");

    return 0;
}

static void __exit misc_exit(void)
{
    //注册杂项设备
    misc_deregister(&misc_dev);
    printk("misc_deregister suceed");
    return;
}











module_init(misc_init);
module_exit(misc_exit);
MODULE_LICENSE("GPL");